package com.dgut.app.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dgut.app.service.FileService;
import com.dgut.common.config.OssProperties;
import com.dgut.common.entity.Attachment;
import com.dgut.common.mapper.AttachmentMapper;
import com.dgut.common.utils.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author IT00ZYQ
 * @Date 2021/4/5 15:45
 **/
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    private final AttachmentMapper attachmentMapper;

    public FileServiceImpl(AttachmentMapper attachmentMapper) {
        this.attachmentMapper = attachmentMapper;
    }

    @Override
    public Attachment uploadFile(MultipartFile file) {
        InputStream inputStream = null;
        OSS ossClient = null;
        try {
            // 1.获取上传文件的输入流
            inputStream = file.getInputStream();
            // 2.获取文件名称
            String filename = file.getOriginalFilename();

            // 3.在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid + filename;

            // 4.创建一个与OSS服务器的链接
            ossClient = new OSSClientBuilder().build(OssProperties.ePoint, OssProperties.keyId, OssProperties.secret);

            // 5.调用oss方法实现上传(Bucket名称,传到oss文件路径和文件名称,上传文件输入流)
            ossClient.putObject(OssProperties.bName, filename, inputStream);

            String url = "https://" + OssProperties.bName+"."+ OssProperties.ePoint +"/" + filename;

            // 6.返回访问文件信息
            return save(url, file.getSize(), file.getOriginalFilename());
        } catch (IOException e) {
            log.error("【文件上传失败】:{}", e.getMessage());
            throw new ApiException("上传文件失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("【关闭文件流失败】");
                }
            }
        }
    }

    /**
     * 保存文件信息到数据库
     * @param url 访问文件的url
     * @param size 文件大小
     * @param fileName 文件名称
     * @return 文件信息
     */
    private Attachment save(String url, long size, String fileName) {
        Attachment attachment = Attachment.builder()
                .fileName(fileName)
                .fileUrl(url)
                .size((int)(size / 1024))
                .build();
        attachmentMapper.insert(attachment);
        return attachment;
    }

}
